package com.myrock.zlbandy.gorock.rock.ui;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TableLayout;
import android.widget.TextView;
import com.etsy.android.grid.StaggeredGridView;
import com.myrock.zlbandy.gorock.HttpModel.ParseInfo;
import com.myrock.zlbandy.gorock.HttpModel.Model.RockInfo;
import com.myrock.zlbandy.gorock.R;
import com.myrock.zlbandy.gorock.my.adapter.MyGridViewAdapter;

import java.util.ArrayList;

public class MySearch extends BaseActivity implements AbsListView.OnItemClickListener,TextView.OnClickListener{

    private  String TAG ="SEARCH";
    private StaggeredGridView gridView;
    private int page = 1;
    private ArrayList<RockInfo> rockInfoall = new ArrayList<RockInfo>();
    private TextView txtFooterTitle;
    private EditText search;
    private TextView nothing;
    private String value;
    private TextView hot1,hot2,hot3,hot4,hot5,hot6;
    private TableLayout hot_search;
    private ProgressBar myProgressBar;
    private TextView textView;

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_search);

        TextView back = (TextView)findViewById(R.id.back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MySearch.this.finish();
            }
        });

        search = (EditText)findViewById(R.id.search_rock);
        search.setHintTextColor(Color.parseColor("#787878"));
        search.setMaxLines(1);
        search.setImeOptions(EditorInfo.IME_ACTION_SEARCH);


        textView = (TextView) findViewById(R.id.tvs);
        textView.setVisibility(View.GONE);
        myProgressBar = (ProgressBar) findViewById(R.id.progressBar);
        myProgressBar.setVisibility(View.GONE);

        LayoutInflater layoutInflater = getLayoutInflater();
        final View footer = layoutInflater.inflate(R.layout.list_item_header_footer, null);

        hot1 = (TextView)findViewById(R.id.hot1);
        hot2 = (TextView)findViewById(R.id.hot2);
        hot3 = (TextView)findViewById(R.id.hot3);
        hot4 = (TextView)findViewById(R.id.hot4);
        hot5 = (TextView)findViewById(R.id.hot5);
        hot6 = (TextView)findViewById(R.id.hot6);
        hot1.setOnClickListener(this);
        hot2.setOnClickListener(this);
        hot3.setOnClickListener(this);
        hot4.setOnClickListener(this);
        hot5.setOnClickListener(this);
        hot6.setOnClickListener(this);

        hot_search = (TableLayout)findViewById(R.id.hot_search);


        gridView = (StaggeredGridView) this.findViewById(R.id.search_view);
        gridView.addFooterView(footer);
        gridView.setOnItemClickListener(this);

        txtFooterTitle =  (TextView) footer.findViewById(R.id.txt_title);
        nothing = (TextView)findViewById(R.id.nothing);

        int margin = 10;
        // set the GridView margin
        gridView.setPadding(margin, 0, margin, 0); // have the margin on the sides as well

        search.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEND
                        || actionId == EditorInfo.IME_ACTION_DONE
                        || (event != null && KeyEvent.KEYCODE_ENTER == event.getKeyCode() && KeyEvent.ACTION_DOWN == event.getAction())) {
                    page = 1;
                    nothing.setVisibility(View.GONE);
                    value = search.getText().toString();
                    search.setText(value);
                    clearItem();
                    Lodeitem();
                    hot_search.setVisibility(View.GONE);

                }
                return false;
            }
        });

        search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if(s.length() == 0){
                    if(nothing.isShown()){
                        nothing.setVisibility(View.GONE);
                    }
                    hot_search.setVisibility(View.VISIBLE);
                    clearItem();

                }
            }
        });
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        Intent intent  = new Intent(MySearch.this,RockInfoActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("rockInfo",rockInfoall.get(position));
        intent.putExtras(bundle);
        startActivity(intent);
    }



    @Override
    public void onClick(View v) {
        nothing.setVisibility(View.GONE);
        hot_search.setVisibility(View.GONE);
        TextView textView =  (TextView)findViewById(v.getId());
        search.setText(textView.getText().toString());
        value = textView.getText().toString();
        clearItem();
        Lodeitem();
    }

    private void Lodeitem(){
        ListTask listTask = new ListTask(myProgressBar,textView,getApplicationContext());
        listTask.execute(value);

    }

    private void clearItem(){
        txtFooterTitle.setText("");
        rockInfoall.clear();
        MyGridViewAdapter adapter = new MyGridViewAdapter(MySearch.this, R.layout.activity_custom_grid_view,
                rockInfoall, new int[]{R.id.imageView1});
        gridView.setAdapter(adapter);
        gridView.deferNotifyDataSetChanged();
        adapter.notifyDataSetChanged();
        search.clearFocus();
    }


    //内部类异步加载

    class ListTask extends AsyncTask<String, Integer, ArrayList<RockInfo>> {

        ProgressBar myprogressbar = null;
        //MainActivity的文本
        TextView textView = null;
        // MainActivity的上下文
        Context mycontext = null;
        //onPreExecute方法用于在执行后台任务前做一些UI操作
        public ListTask(ProgressBar progressbar, TextView textview, Context context) {
            myprogressbar = progressbar;
            mycontext = context;
            textView = textview;
        }
        @Override
        protected void onPreExecute() {
            Log.i(TAG, "onPreExecute() called");
            textView.setVisibility(View.VISIBLE);
            myProgressBar.setVisibility(View.VISIBLE);
            textView.setText("正在搜索...");
            myprogressbar.setProgress(10);

        }

        //doInBackground方法内部执行后台任务,不可在此方法内修改UI
        @Override
        protected ArrayList<RockInfo> doInBackground(String... params) {
            ArrayList<RockInfo> arrayList = new ArrayList<RockInfo>();
            arrayList = ParseInfo.GetRock(value,page);
            for(int i = 50;i<99;i++){
                publishProgress(i);
            }
            return arrayList;


        }



        //onProgressUpdate方法用于更新进度信息
        @Override
        protected void onProgressUpdate(Integer... progresses) {
            Log.i(TAG, "onProgressUpdate(Progress... progresses) called");
            int progress = myprogressbar.getMax() / 100 * (progresses[0] + 1);
            myprogressbar.setProgress(progress);
            textView.setText("正在搜索..." + progress + "%");
        }

        //onPostExecute方法用于在执行完后台任务后更新UI,显示结果
        @Override
        protected void onPostExecute(ArrayList<RockInfo> result) {
            myprogressbar.setVisibility(View.GONE);
            textView.setVisibility(View.GONE);
            if(result.size()>0 && result.size()<10){
                rockInfoall.addAll(result);
                MyGridViewAdapter adapter = new MyGridViewAdapter(MySearch.this, R.layout.activity_custom_grid_view,
                        rockInfoall, new int[]{R.id.imageView1});
                gridView.setAdapter(adapter);
                adapter.notifyDataSetChanged();
                txtFooterTitle.setTextColor(Color.parseColor("#000000"));
                txtFooterTitle.setText("没有更多");
            }else if(result.size()>0 && result.size()==10){
                rockInfoall.addAll(result);
                MyGridViewAdapter adapter = new MyGridViewAdapter(MySearch.this, R.layout.activity_custom_grid_view,
                        rockInfoall, new int[]{R.id.imageView1});
                gridView.setAdapter(adapter);
                adapter.notifyDataSetChanged();
                txtFooterTitle.setText("下一页");
                txtFooterTitle.setTextColor(Color.parseColor("#0099da"));
                txtFooterTitle.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        page++;
                        Lodeitem();
                    }
                });
            }else{

                nothing.setText("没有搜索到任何矿石...");
                nothing.setVisibility(View.VISIBLE);
                hot_search.setVisibility(View.VISIBLE);
            }

        }

        //onCancelled方法用于在取消执行中的任务时更改UI
        @Override
        protected void onCancelled() {
            Log.i(TAG, "onCancelled() called");

        }
    }
}
